# -*- coding: latin-1 -*-
#=========================================================================================
from Code.Constantes import *

import collections

from PyQt4 import QtGui, QtCore

import Code.TrListas as TrListas

import Code.QT.Iconos as Iconos
import Code.QT.Controles as Controles
import Code.QT.QTVarios as QTVarios
import Code.QT.QTUtil as QTUtil
import Code.QT.QTUtil2 as QTUtil2
import Code.QT.FormLayout as FormLayout

import Code.QT.WBG_Comun as WBG_Comun

SIN_VALORACION, MUY_MALO, MALO, BUENO, MUY_BUENO, INTERESANTE, DUDOSA = (0,4,2,1,3,5,6)
V_SIN, V_IGUAL, V_BLANCAS, V_NEGRAS, V_BLANCAS_MAS, V_NEGRAS_MAS, V_BLANCAS_MAS_MAS, V_NEGRAS_MAS_MAS = (0,11,14,15,16,17,18,19)

#=========================================================================================
class TreeMoves(QtGui.QTreeWidget):
    def __init__(self, wmoves):
        QtGui.QTreeWidget.__init__(self)
        self.wmoves = wmoves
        self.itemActivo = None
        self.setAlternatingRowColors(True)

        self.dicItems = {}

        self.posMoves = 0
        self.posTransposition = 1
        self.posBookmark = 2
        self.posAnalisis = 3
        self.posComment = 4
        self.setHeaderLabels( (_("Moves"),"", "", _( "Analysis" ), _( "Comments" ), "") )
        self.setColumnHidden(5,True)
        self.setIndentation(14)
        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.menuContexto)

        self.setStyleSheet("selection-background-color: #F1D369; selection-color: #000000;")

        ftxt = Controles.TipoLetra( puntos=9 )

        self.setFont(ftxt)

        self.connect( self, QtCore.SIGNAL( "itemExpanded(QTreeWidgetItem *)" ), self.expandido )
        self.connect( self, QtCore.SIGNAL( "itemSelectionChanged()" ), self.seleccionadoISC )
        self.connect( self, QtCore.SIGNAL( "itemDoubleClicked(QTreeWidgetItem *,int)" ), self.dobleClick )

        self.noIcon = QtGui.QIcon()
        self.iconBookmark = Iconos.Favoritos()
        self.iconTransposition = Iconos.Transposition()

        listNAGs = TrListas.listNAGs()
        self.dicValoracion = collections.OrderedDict()
        self.dicValoracion[BUENO] = (listNAGs[1],Iconos.JG_Buena())
        self.dicValoracion[MALO] = (listNAGs[2],Iconos.JG_Mala())
        self.dicValoracion[MUY_BUENO] = (listNAGs[3],Iconos.JG_MuyBuena())
        self.dicValoracion[MUY_MALO] = (listNAGs[4],Iconos.JG_MuyMala())
        self.dicValoracion[INTERESANTE] = (listNAGs[5],Iconos.JG_Interesante())
        self.dicValoracion[DUDOSA] = (listNAGs[6],Iconos.JG_Dudosa())
        self.dicValoracion[SIN_VALORACION] = (_("No rating"),self.noIcon )#Iconos.JG_SinValoracion())

        self.dicVentaja = collections.OrderedDict()
        self.dicVentaja[V_SIN] = ( _("Undefined"), self.noIcon )
        self.dicVentaja[V_IGUAL] = ( listNAGs[11], Iconos.V_Blancas_Igual_Negras() )
        self.dicVentaja[V_BLANCAS] = ( listNAGs[14], Iconos.V_Blancas() )
        self.dicVentaja[V_BLANCAS_MAS] = ( listNAGs[16], Iconos.V_Blancas_Mas() )
        self.dicVentaja[V_BLANCAS_MAS_MAS] = ( listNAGs[18], Iconos.V_Blancas_Mas_Mas() )
        self.dicVentaja[V_NEGRAS] = ( listNAGs[15], Iconos.V_Negras() )
        self.dicVentaja[V_NEGRAS_MAS] = ( listNAGs[17], Iconos.V_Negras_Mas() )
        self.dicVentaja[V_NEGRAS_MAS_MAS] = ( listNAGs[19], Iconos.V_Negras_Mas_Mas() )

    #--------------------------------------------------------------------------------------------------------------------------------
    def dobleClick(self, item, col):
        move = self.dicItems.get(str(item), None)
        if move is None :
            return

        elif col == self.posTransposition :
            tr = move.transpositions()
            ntr = len(tr)
            if ntr == 0 :
                return
            menutr = QTVarios.LCMenu()
            menutr.opcion( None, move.allPGN(), Iconos.Transposition(), siDeshabilitado=True )
            menutr.separador()
            for n,mv in enumerate(tr) :
                menutr.opcion( "tr_%d"%n, mv.allPGN(), Iconos.PuntoVerde() )
            resp = menutr.lanza()
            if resp :
                move = tr[int(resp[3:])]

                self.wmoves.seleccionaMove( move )

        elif col == self.posAnalisis :
            rm = move.analisis()
            if rm :
                fen = move.father().fen()
                pv = move.pv()+" "+rm.pv
                self.analisis.showAnalisis(fen, pv, rm )

    #--------------------------------------------------------------------------------------------------------------------------------
    def setBookGuide( self, bookGuide ) :
        self.bookGuide = bookGuide
        self.analisis = WBG_Comun.Analisis(self, bookGuide, self.resetAnalisis)

    #--------------------------------------------------------------------------------------------------------------------------------
    def menuContexto( self, position):
        item, move = self.moveActual()
        if not move :
            return

        menu = QTVarios.LCMenu()

        menu.opcion( "expand", _("Expand"), Iconos.Mas22() )
        menu.separador()
        menu.opcion( "collapse", _("Collapse"), Iconos.Menos22() )
        menu.separador()
        menu.opcion( "remove", _("Remove"), Iconos.Borrar() )
        menu.separador()
        padre = move.father()
        fenM2 = padre.fenM2()
        rmAnalisis = move.analisis()
        siShowMoves = rmAnalisis is not None
        self.analisis.menuAnalizar( fenM2, menu, siShowMoves )
        menu.separador()
        if move.mark() :
            menu.opcion( "mark_rem", _("Remove bookmark"), self.iconBookmark )
        else :
            menu.opcion( "mark_add", _("Add bookmark"), self.iconBookmark )

        tr = move.transpositions()
        if tr :
            menu.separador()
            menutr = menu.submenu( _("Transpositions"), Iconos.Transposition() )
            for n,mv in enumerate(tr) :
                menutr.opcion( "tr_%d"%n, mv.allPGN(), Iconos.PuntoVerde() )
                menutr.separador()

        resp = menu.lanza()
        if resp :
            if resp == "expand" :
                self.showFrom(move, True)
                self.resizeColumnToContents( 0 )

            elif resp == "collapse" :
                self.showFrom(move, False)

            elif resp == "remove" :
                self.borrar()

            elif resp.startswith( "mark_rem" ) :
                move.mark("")
                self.ponIconoBookmark(item, move.mark())
                self.wmoves.compruebaBookmarks()

            elif resp.startswith( "mark_add" ) :
                self.newBookmark(move)

            elif resp.startswith( "tr_" ) :
                self.wmoves.seleccionaMove( tr[int(resp[3:])] )

            elif resp.startswith( "an_" ) :
                fen = padre.fen()
                pv = move.pv()+" "+rmAnalisis.pv if siShowMoves else None
                self.analisis.exeAnalizar( fenM2, resp, padre, fen, pv, rmAnalisis )

    #--------------------------------------------------------------------------
    def showUnMove(self, itemBase, unMove):
        if unMove.item() is None :
            pgn = unMove.pgnNum()
            comentario = unMove.comment()
            posicion = str(unMove.pos())
            puntos = unMove.etiPuntos()
            item = QtGui.QTreeWidgetItem( itemBase, [pgn, "","",puntos, comentario, posicion] )
            item.setTextAlignment(self.posAnalisis, QtCore.Qt.AlignRight)
            self.ponIconoValoracion( item, unMove.nag() )
            self.ponIconoVentaja( item, unMove.adv() )
            self.ponIconoBookmark( item, unMove.mark() )
            if unMove.transpositions() :
                item.setIcon( self.posTransposition, self.iconTransposition )
            self.dicItems[str(item)] = unMove
            unMove.item(item)

    #--------------------------------------------------------------------------
    def showFrom(self, unMove, siExpand):

        if siExpand :
            mens = QTUtil2.mensEspera
            mens.inicio( self, _("Expanding"), siCancelar = True )

        def work( move ) :
            if siExpand and mens.cancelado() :
                return
            itemBase = move.item()

            for uno in move.children() :
                if uno.item() is None :
                    self.showUnMove( itemBase, uno )
                if siExpand :
                    uno.item().setExpanded(True)
                    work(uno)
            itemBase.setExpanded(siExpand)

        work( unMove )
        if siExpand :
            mens.final()

    #--------------------------------------------------------------------------
    def showChildren(self, unMove, siNietos):
        itemBase = unMove.item()

        for uno in unMove.children() :
            if uno.item() is None :
                self.showUnMove( itemBase, uno )
            if siNietos :
                self.showChildren(uno,False)
        self.resizeColumnToContents( 0 )

    #--------------------------------------------------------------------------------------------------------------------------------
    def focusInEvent( self, event ) :
        self.seleccionado( self.itemActivo )
        self.wmoves.focusInEvent(event)

    #--------------------------------------------------------------------------------------------------------------------------------
    def moveActual( self ) :
        item = self.itemActivo
        if item :
            mov = self.dicItems[str(item)]
        else :
            mov = None
        return item, mov

    #--------------------------------------------------------------------------
    def seleccionadoISC(self):
        self.itemActivo = self.currentItem()
        self.seleccionado( self.itemActivo )

    #--------------------------------------------------------------------------
    def seleccionado(self, item):
        if item :
            uno = self.dicItems[str(item)]
            self.wmoves.seleccionado(uno)
            self.resizeColumnToContents( self.posMoves )

    #--------------------------------------------------------------------------
    def expandido(self, item):
        uno = self.dicItems[str(item)]
        self.showChildren(uno,True)

    #--------------------------------------------------------------------------
    def ponIconoVentaja(self, item, ventaja):
        if ventaja not in self.dicVentaja :
            ventaja = 0
        item.setIcon( self.posAnalisis, self.dicVentaja[ventaja][1] )

    #--------------------------------------------------------------------------
    def ponIconoValoracion(self, item, valoracion):
        item.setIcon( self.posMoves, self.dicValoracion[valoracion][1] )

    #--------------------------------------------------------------------------
    def ponIconoBookmark(self, item, mark):
        ico = self.iconBookmark if mark else self.noIcon
        item.setIcon( self.posBookmark, ico )

    #--------------------------------------------------------------------------
    # def showChildrenPV(self, moveRoot, pv):
        # self.showChildren( moveRoot, True)
        # if not pv :
            # return

        # unMove = moveRoot
        # li = pv.split(" ")
        # for unPV in li :
            # ok = False
            # for uno in unMove.children() :
                # if uno.pv() == unPV :
                    # ok = True
                    # unMove = uno
                    # break
            # if ok :
                # self.showChildren( unMove, True)
            # else :
                # break
        # item = unMove.item()
        # self.scrollToItem(item)
        # self.setCurrentItem(item)
        # self.seleccionado(item)

    #--------------------------------------------------------------------------
    def resetValoracion(self, move ):
        self.ponIconoValoracion( move.item(), move.nag() )

    #--------------------------------------------------------------------------
    def resetVentaja(self, move ):
        self.ponIconoVentaja( move.item(), move.adv() )

    #--------------------------------------------------------------------------
    def resetComentario(self, move ):
        if move.pv() :
            move.item().setText( self.posComment, move.comment())

    #--------------------------------------------------------------------------------------------------------------------------------
    def resetAnalisis(self, padre ):
        for uno in padre.children() :
            item = uno.item()
            item.setText( self.posAnalisis, uno.etiPuntos())

    #--------------------------------------------------------------------------
    def borrar(self):
        item,mov = self.moveActual()
        if item :
            if QTUtil2.pregunta( self, _X(_( "Delete %1 ?"), mov.pgn()) ) :
                um = QTUtil2.unMomento(self)
                self.removeRow()
                liBorrados, liQuitarTransposition = self.bookGuide.borrar(mov)
                for mv in liBorrados :
                    item = mv.item()
                    if item :
                        del self.dicItems[str(item)]
                for mv in liQuitarTransposition :
                    item = mv.item()
                    if item :
                        item.setIcon(self.posTransposition, QtGui.QIcon())

                um.final()
                self.wmoves.compruebaBookmarks()

    #--------------------------------------------------------------------------
    def removeRow(self):
        index = self.currentIndex()
        model = self.model()
        model.removeRow(index.row(), index.parent())

    #--------------------------------------------------------------------------
    def newBookmark(self, move):

        comment = move.comment()
        allpgn = move.allPGN()
        siComment = len(comment)>0

        txt = comment if siComment else allpgn

        liGen = [(None,None)]
        liGen.append( ( _( "Name" ) + " :", txt ) )

        liGen.append( ( _( "Copy PGN" ) + " :", False ) )
        if siComment :
            liGen.append( ( _( "Copy comment" ) + " :", False ) )

        reg = KRegistro()
        reg.allpgn = allpgn
        reg.comment = comment.split("\n")[0].strip()
        reg.form = None

        def dispatch( valor ) :
            if reg.form is None :
                reg.form = valor
                reg.wname = valor.getWidget(0)
                reg.wpgn = valor.getWidget(1)
                reg.wcomment = valor.getWidget(2)
                reg.wpgn.setText( reg.allpgn )
                if reg.wcomment :
                    reg.wcomment.setText(reg.comment)
            else :
                QTUtil.refreshGUI()
                if reg.wpgn.isChecked() :
                    reg.wname.setText(reg.allpgn)
                elif reg.wcomment and reg.wcomment.isChecked() :
                    reg.wname.setText(reg.comment)
                if reg.wcomment :
                    reg.wcomment.setChecked(False)
                reg.wpgn.setChecked(False)
                QTUtil.refreshGUI()

        resultado = FormLayout.fedit( liGen, title="Bookmark", parent = self.wmoves, anchoMinimo = 460, icon = Iconos.Favoritos(), dispatch=dispatch )
        if resultado is None :
            return None

        accion, liResp = resultado
        txt = liResp[0].strip()
        if txt :
            move.mark(txt)
            self.ponIconoBookmark(move.item(),move.mark())
            self.wmoves.compruebaBookmarks()
